package com.itheima.reggie.controller;

import com.alibaba.fastjson.serializer.AdderSerializer;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.AddressBook;
import com.itheima.reggie.service.AddressBook.AddressBookService;
import com.itheima.reggie.service.AddressBook.Impl.AddressBookImplService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 地址 管理
 */
@RestController
@RequestMapping("/addressBook")
@Slf4j
public class AddressBookController {
    @Autowired
    AddressBookImplService addressBookImplService;

    /**
     * 新增
     * @param addressBook
     * @return
     */
    @PostMapping
    public R<AddressBook> save(@RequestBody AddressBook addressBook){
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookImplService.save(addressBook);
        return R.success(addressBook);
    }

    /**
     * 设置默认地址
     * @param addressBook
     * @return
     */

    @PutMapping("/default")
    public R<AddressBook> setDefault(@RequestBody AddressBook addressBook){
        LambdaUpdateWrapper<AddressBook> lambdaUpdateChainWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateChainWrapper.eq(AddressBook::getUserId,BaseContext.getCurrentId());
        lambdaUpdateChainWrapper.set(AddressBook::getIsDefault,0);
        addressBookImplService.update(lambdaUpdateChainWrapper);
        addressBook.setIsDefault(1);
        addressBookImplService.updateById(addressBook);
        return R.success(addressBook);
    }

    @GetMapping("/default")
    public R<AddressBook> GetDefault(){
        LambdaUpdateWrapper<AddressBook> lambdaUpdateChainWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateChainWrapper.eq(AddressBook::getUserId,BaseContext.getCurrentId());
        lambdaUpdateChainWrapper.eq(AddressBook::getIsDefault,1);
        AddressBook one = addressBookImplService.getOne(lambdaUpdateChainWrapper);
        return R.success(one);
    }

    /**
     * 查询指定用户的全部地址
     * @param addressBook
     * @return
     */
    @GetMapping("/list")
    public R<List<AddressBook>> list(AddressBook addressBook){
        System.out.println(addressBook);
        addressBook.setUserId(BaseContext.getCurrentId());

        LambdaQueryWrapper<AddressBook> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(addressBook.getUserId() != null,AddressBook::getUserId,addressBook.getUserId());
        lambdaQueryWrapper.orderByDesc(AddressBook::getUpdateTime);

        return R.success(addressBookImplService.list(lambdaQueryWrapper));
    }


}
